package com.yangtu.nearbyshop.admin.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangtu.nearbyshop.admin.annotation.RequiresPermissionsDesc;
import com.yangtu.nearbyshop.admin.dao.MercInf;
import com.yangtu.nearbyshop.admin.service.AdminMercService;
import com.yangtu.nearbyshop.admin.service.AdminOrderService;
import com.yangtu.nearbyshop.admin.util.AdminResponseCode;
import com.yangtu.nearbyshop.core.qcode.QCodeService;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.core.validator.Order;
import com.yangtu.nearbyshop.core.validator.Sort;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.NearbyshopMercService;
import com.yangtu.nearbyshop.db.service.NearbyshopUserService;
import com.yangtu.nearbyshop.db.service.itf.*;
import com.yangtu.nearbyshop.db.util.MercUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yangtu.nearbyshop.core.corg.Const.CMM_PARAM_RETURN_MSG;

@RestController
@RequestMapping("/admin/merc")
@Validated
public class AdminMercController {
    private final Log logger = LogFactory.getLog(AdminMercController.class);


    /**
     * @apiDefine merc 团长相关接口
     *
     */

    @Autowired
    private AdminMercService mercService;

    @Autowired
    private AdminOrderService orderService;

    @Autowired
    private INearbyshopOrderService nearbyshopOrderService;

    @Autowired
    private NearbyshopMercService nearbyshopMercService;

    @Autowired
    private INearbyshopMercService plusMercService;

    @Autowired
    private INearbyshopMercSettleService mercSettleService;

    @Autowired
    private INearbyshopBdService bdService;

    @Autowired
    private INearbyshopMercRebateService rebateService;

    @Autowired
    private INearbyshopMercRebateSettleService rebateSettleService;

    @Autowired
    private NearbyshopUserService userService;

    @Autowired
    private QCodeService qCodeService;

    @RequiresPermissions("admin:merc:list")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="查询")
    @GetMapping("/list")
    public Object list(String mercNm, String mobile,String mercNo,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {

        return mercService.list(mercNm, mobile, mercNo,page, limit, sort, order);
    }

    /**
     * @api {GET} /admin/merc/listSon 查询下级
     * @apiName merc listSon
     * @apiGroup merc
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {String} mercNo 团长编号
     *  @apiParam {int} level  1:一级下线  2：二级
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:merc:listSon")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="查询下级")
    @GetMapping("/listSon")
    public Object listSon(@RequestParam String mercNo,
                          @RequestParam(defaultValue = "1") Integer level,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopMerc2> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);

        IPage<NearbyshopMerc2> pList = plusMercService.getSonList(pageVo,mercNo,level);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:merc:detail")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        return mercService.detail(id);
    }

    @RequiresPermissions("admin:merc:delete")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="删除")
    @GetMapping("/delete")
    public Object delete(@NotNull Integer id) {
        NearbyshopMerc merc = nearbyshopMercService.findById(id);
        int count = nearbyshopOrderService.count(new QueryWrapper<NearbyshopOrder2>()
            .eq("merc_no",merc.getMercNo())
            .eq("deleted",0));
        if(count > 0){
            return ResponseUtil.fail(AdminResponseCode.MERC_DELETE_INVALID,
                    "存在相关订单，请联系管理员修改");
        }
        return mercService.delete(id);
    }

    @RequiresPermissions("admin:merc:update")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="编辑")
    @PostMapping("/update")
    public Object update(@RequestBody MercInf mercInf) {
        if(!StringUtils.isEmpty(mercInf.getBdNo())){
            NearbyshopBd bd = bdService.getOne(new QueryWrapper<NearbyshopBd>()
                    .eq("bd_no",mercInf.getBdNo())
                    .eq("deleted",0));
            if(bd == null){
                return ResponseUtil.fail("BD不存在");
            }
        }
        if(mercInf.getLevel().equals("101")){
            if(!StringUtils.isEmpty(mercInf.getReferMerc())){
                NearbyshopMerc2 merc = plusMercService.getOne(new QueryWrapper<NearbyshopMerc2>()
                    .eq("merc_no",mercInf.getReferMerc()));
                if(merc == null){
                    return ResponseUtil.fail("推荐人不存在");
                }else if(!merc.getLevel().equals("101")){
                    return ResponseUtil.fail("推荐人非一级总代");
                }
            }
        }

        if(userService.queryByMobile(mercInf.getMobile()).size()==0){
            return ResponseUtil.fail("手机号未注册用户");
        }
        return mercService.update(mercInf);
    }

    @RequiresPermissions("admin:merc:create")
    @RequiresPermissionsDesc(menu={"团长管理" , "新增团长"}, button="添加")
    @PostMapping("/create")
    public Object add(@RequestBody MercInf mercInf) {
        if(!StringUtils.isEmpty(mercInf.getBdNo())){
            NearbyshopBd bd = bdService.getOne(new QueryWrapper<NearbyshopBd>()
                    .eq("bd_no",mercInf.getBdNo())
                    .eq("deleted",0));
            if(bd == null){
                return ResponseUtil.fail("BD不存在");
            }
        }

        if(mercInf.getLevel().equals("101")){
            if(!StringUtils.isEmpty(mercInf.getReferMerc())){
                NearbyshopMerc2 merc = plusMercService.getOne(new QueryWrapper<NearbyshopMerc2>()
                        .eq("merc_no",mercInf.getReferMerc()));
                if(merc == null){
                    return ResponseUtil.fail("推荐人不存在");
                }else if(!merc.getLevel().equals("101")){
                    return ResponseUtil.fail("推荐人非一级总代");
                }
            }
        }
        return mercService.create(mercInf);
    }

    @RequiresPermissions("admin:merc:profit")
    @RequiresPermissionsDesc(menu={"团长管理" , "提成明细"}, button="查询提成")
    @GetMapping("/profit")
    public Object profit(String mercNo, String startDt, String endDt,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer limit) {
        return orderService.getProfitList(mercNo, startDt, endDt, page, limit);
    }

    /**
     * @api {GET} /admin/merc/close 停业
     * @apiName merc close
     * @apiGroup merc
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {int} id 团长id
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:merc:close")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="停业")
    @GetMapping("/close")
    public Object close(@NotNull Integer id) {
        NearbyshopMerc merc = new NearbyshopMerc();
        merc.setId(id);
        merc.setStatus(MercUtil.STATUS_CLOSE);
        nearbyshopMercService.updateById(merc,null);
        return ResponseUtil.ok();
    }

    /**
     * @api {GET} /admin/merc/open 开业
     * @apiName merc open
     * @apiGroup merc
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {int} id 团长id
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:merc:open")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="开业")
    @GetMapping("/open")
    public Object open(@NotNull Integer id) {
        NearbyshopMerc merc = new NearbyshopMerc();
        merc.setId(id);
        merc.setStatus(MercUtil.STATUS_NORMAL);
        nearbyshopMercService.updateById(merc,null);
        return ResponseUtil.ok();
    }

    /**
     * @api {GET} /admin/merc/weekSettle 门店周营业额
     * @apiName merc weekSettle
     * @apiGroup merc
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {String} [mercName] 门店名称
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:merc:weekSettle")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="门店周营业额")
    @GetMapping("/weekSettle")
    public Object weekSettle(String mercName,
                        @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer limit){
        Page<NearbyshopMerc2> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopMerc2> pList = plusMercService.page(pageVo,
                new QueryWrapper<NearbyshopMerc2>()
            .eq(!StringUtils.isEmpty(mercName),"merc_name",mercName)
            .eq("deleted",0));
        for(NearbyshopMerc2 merc: pList.getRecords()){
            Page<NearbyshopMercSettle> pg = new Page<>();
            pg.setCurrent(1);
            pg.setSize(10);
            IPage<NearbyshopMercSettle> settles = mercSettleService.getMercSettleList(pg,merc.getMercNo());
            merc.setSettleList(settles.getRecords());
        }
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/merc/timeRebate 实时返利
     * @apiName merc timeRebate
     * @apiGroup merc
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {String} [startTime] 开始时间
     * @apiParam {String} [endTime] 结束时间
     * @apiParam {String} [mercNo] 门店编码
     * @apiParam {String} [mercName] 门店名称
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:merc:timeRebate")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="实时返利")
    @GetMapping("/timeRebate")
    public Object timeRebate(String mercName,String mercNo,String startTime,String endTime,
                        @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer limit){
        if(!StringUtils.isEmpty(startTime)){
            startTime += " 00:00:00";
        }
        if(!StringUtils.isEmpty(endTime)){
            startTime += " 23:59:59";
        }
        Page<NearbyshopMercRebate> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopMercRebate> pList = rebateService.getTimeRebate(pageVo,
                mercName,mercNo,startTime,endTime);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/merc/dailyRebate 日返利
     * @apiName merc dailyRebate
     * @apiGroup merc
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {String} [startTime] 开始时间
     * @apiParam {String} [endTime] 结束时间
     * @apiParam {String} [mercNo] 门店编码
     * @apiParam {String} [mercName] 门店名称
     * @apiParam {int} page 页码
     * @apiParam {int} limit 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:merc:dailyRebate")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长列表"}, button="日返利")
    @GetMapping("/dailyRebate")
    public Object dailyRebate(String mercName,String mercNo,String startTime,String endTime,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer limit){
        Page<NearbyshopMercRebateSettle> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopMercRebateSettle> pList = rebateSettleService.getDailyRebateSettle(pageVo,
                mercName,mercNo,startTime,endTime);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:merc:qrcode")
    @RequiresPermissionsDesc(menu={"团长管理" , "团长信息"}, button="团长二维码")
    @GetMapping("/qrcode")
    public Object add(@NotNull Integer id) {
        NearbyshopMerc merc = nearbyshopMercService.findById(id);
        if(null == merc){
            ResponseUtil.fail("团长或总代不存在");
        }
        String qrcode = "";
        if(StringUtils.isEmpty(merc.getQrCode())){
            qrcode = qCodeService.createMercImage(merc.getMercNo());
            merc.setQrCode(qrcode);
            nearbyshopMercService.updateById(merc,null);
        }else {
            qrcode = merc.getQrCode();
        }

        return ResponseUtil.ok(qrcode);
    }
}
